package com.school.teaching.controller;

import java.util.Arrays;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.school.teaching.dto.OrganizationQueryDTO;
import com.school.teaching.entity.Organization;
import com.school.teaching.exception.ServiceException;
import com.school.teaching.json.JSONMessage;
import com.school.teaching.service.IOrganizationService;

@RestController
@RequestMapping("/manager/organization")
public class OrganizationController {
	
	private final static Logger LOGGER = LoggerFactory
			.getLogger(OrganizationController.class);

	@Autowired
	private IOrganizationService organizationService;
	
	@RequestMapping(value = "/query", method = RequestMethod.GET)
	public Object query(OrganizationQueryDTO param) {
		return organizationService.query(param);
	}
	
	@RequestMapping(value = "/saveOrUpdate", method = RequestMethod.POST)
	@ResponseBody
	public Object saveOrUpdate(Organization organization) {
		JSONMessage jMessage = new JSONMessage();
		try {
			organizationService.saveOrUpdate(organization);
			jMessage.setStatus(Boolean.TRUE);
		} catch (Exception e) {
			LOGGER.error("保存数据失败", e);
			jMessage.setStatus(Boolean.FALSE);
			if (e instanceof ServiceException) {
				jMessage.setMessage(e.getMessage());
			} else {
				jMessage.setMessage("系统异常");
			}
		}
		return jMessage;
	}
	
	@RequestMapping("/deleteBatch")
	@ResponseBody
	public Object deleteBatch(String ids) {
		JSONMessage jMessage = new JSONMessage();
		try {
			organizationService.deleteByIds(Arrays.asList(StringUtils
					.commaDelimitedListToStringArray(ids)));
			jMessage.setStatus(Boolean.TRUE);
		} catch (Exception e) {
			LOGGER.error("删除数据失败", e);
			jMessage.setStatus(Boolean.FALSE);
			if (e instanceof ServiceException) {
				jMessage.setMessage(e.getMessage());
			} else {
				jMessage.setMessage("系统异常");
			}
		}
		return jMessage;
	}
	
	@RequestMapping("/getById")
	@ResponseBody
	public Object getById(String id) {
		JSONMessage jMessage = new JSONMessage();
		try {
			Organization data = organizationService.getById(id);
			jMessage.setStatus(Boolean.TRUE);
			jMessage.setData(data);
		} catch (Exception e) {
			LOGGER.error("获取数据失败", e);
			jMessage.setStatus(Boolean.FALSE);
			if (e instanceof ServiceException) {
				jMessage.setMessage(e.getMessage());
			} else {
				jMessage.setMessage("系统异常");
			}
		}
		return jMessage;
	}
}
